from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
import database
from google.appengine.api import memcache
import logging

class CommonRoom(webapp.RequestHandler):
	def get(self, name):
		room = database.CommonRoom.get_by_key_name(name)
		if room:
			path = os.path.join(os.path.dirname(__file__), 'templates/commonroom.html')
			self.response.out.write(template.render(path, {
				'room': room,
			}))
		else:
			self.error(404)
			message = 'the room '+name+' does not exist'
			logging.error(message)
			self.response.out.write(message)

class CommonRooms(webapp.RequestHandler):
	def get(self):
		page = memcache.get('commonrooms_page')
		if not page:
			path = os.path.join(os.path.dirname(__file__), 'templates/commonrooms.html')
			page = template.render(path, {'rooms': database.CommonRoom.all()})
			memcache.add("commonrooms_page", page)
		self.response.out.write(page)

class StudentRoom(webapp.RequestHandler):
	def get(self, number):
		room = database.StudentRoom.get_by_key_name(number)
		if room:
			path = os.path.join(os.path.dirname(__file__), 'templates/studentroom.html')
			self.response.out.write(template.render(path, {
				'room': room,
			}))
		else:
			message = 'the room '+number+' does not exist'
			logging.error(message)
			self.error(404)
			self.response.out.write()

application = webapp.WSGIApplication([
		('/commonrooms/', CommonRooms),
		('/commonrooms/(.+)', CommonRoom),
		('/studentrooms/(\d+)', StudentRoom),
	],
	debug=True
)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()


